package com.prs.crm.flow.impl;

import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.context.Constrains;
import com.prs.crm.domain.flow.WorkFlowHandler;
import com.prs.crm.domain.flow.WorkFlowProcessNode;
import com.prs.crm.domain.flow.WorkFlowProcessNodeDetail;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.flow.FlowJudger;
import com.prs.crm.service.flow.WorkFlowProcessService;

public class FlowJudgerImpl implements FlowJudger{

	private WorkFlowProcessService workFlowProcessService;
	
	@Autowired
	public void setWorkFlowProcessService(WorkFlowProcessService workFlowProcessService) {
		this.workFlowProcessService = workFlowProcessService;
	}
	
	public WorkFlowProcessService getWorkFlowProcessService() {
		return workFlowProcessService;
	}
	
	/**
	 * 判断指定的人员审核是否为审核里程碑
	 * @param node
	 * @param person
	 * @return
	 */
	private boolean milestone(WorkFlowProcessNode node,Person person,Integer result)
	{
		/**
		 * 当前情况下，如果是部门角色审批，则任何一人的审批都视为里程碑
		 */
		if (person.getRole()!=null)
		{
			return true;
		}
		else
		{
			WorkFlowHandler handler = node.getHandler();
			/**
			 * 如果为负责人
			 */
			if (person.getId().equals(handler.getPrincipal().getId()))
			{
				return true;
			}
			else
			{
				/**
				 * 如果非负责人审批，则不对该节点的流程状态起效
				 * 
				 */
				return false;
/*				int num = this.getWorkFlowProcessService().
								countProcessNodes(node.getFlowProcess(), Constrains.WORKFLOWPROCESS_STATE_END, 
										result);
				*//**
				 * 当持相同结果的人数大于等于执行人人数
				 *//*
				if (num>=handler.getExecutors().size())
				{
					return true;
				}
				else
				{
					return false;
				}*/
			}
		}
	}
	
	public int judge(WorkFlowProcessNodeDetail nodeDetail)
	{
		if (nodeDetail.getResult().equals(Constrains.WORKFLOWPROCESS_RESULT_PASS))
		{
			return pass(nodeDetail.getProcessNode(),nodeDetail.getExecutor());
		}
		else
		{
			return reject(nodeDetail.getProcessNode(),nodeDetail.getExecutor());
		}
	}
	
	
	public int pass(WorkFlowProcessNode processNode,Person executor)
	{
		if (milestone(processNode,executor,Constrains.WORKFLOWPROCESS_RESULT_PASS))
		{
			return Constrains.WORKFLOWPROCESS_STATE_END;
		}
		else
		{
			return Constrains.WORKFLOWPROCESS_STATE_PROCESS;
		}
	}
	
	public int reject(WorkFlowProcessNode processNode,Person executor)
	{
		if (milestone(processNode,executor,Constrains.WORKFLOWPROCESS_RESULT_NOTPASS))
		{
			return Constrains.WORKFLOWPROCESS_STATE_END;
		}
		else
		{
			return Constrains.WORKFLOWPROCESS_STATE_PROCESS;
		}
	}
}
